<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
         
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/import')"
            >导入excel</el-button
          >
          <el-button
            v-allow="'export'"
            type="danger"
            size="small"
            @click="hExportExcel"
          >导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="hAdd"
          >新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="scope">
              {{ formatType(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id=' + scope.row.id)"
                >查看</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="hAssignRole(scope.row.id)"
                >分配角色</el-button
              >
              <el-button type="text" size="small" @click="dDel(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="total, sizes,prev, pager, next, jumper"
            :total="total"
            :page-size="size"
            :current-page.sync="page"
            :page-sizes="[1, 3, 5, 7, 10]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog title="新增员工" :visible.sync="showDialog">
      <EmpDialog @close="hClose" @success="hUpdateEmpolyee" v-if="showDialog" />
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="showDialogRole">
            <AssignRole
        v-if="showDialogRole"
        :cur-employee-id="curId"
        @success="hSuccessRole"
      />
    </el-dialog>
  </div>
</template>
<script>
import EmployeENUM from "@/constant/employees";
import { getEmployeeList, delDemployees } from "@/api/employees";
import EmpDialog from "./empDialog";
import AssignRole from "./AssignRole.vue";
// console.log("22",EmployeENUM)
export default {
  components: { EmpDialog, AssignRole },
  data() {
    return {
      showDialogRole: false, // 分配角色的弹框
      showDialog: false, // 添加员工的弹出框
      list: [],
      curId: "", // 当前被选中的员工的id
      size: 10,
      page: 1,
      total: 0,
      showDialog: false,
    };
  },
  created() {
    this.loadEmployeeList();
  },
  methods: {
      hSuccessRole() {
      // 关闭弹层
      this.showDialogRole = false
    },
    // 用户点击了分配角色
    hAssignRole(id) {
      this.showDialogRole = true;
      // 保存id，以便父传子
      this.curId = id;
    },
    async loadEmployeeList() {
      const res = await getEmployeeList({ page: this.page, size: this.size });
      this.list = res.data.rows;
      this.total = res.data.total;
    },
    formatType(type) {
      const item = EmployeENUM.hireType.find((item) => item.id === type);
      if (item) {
        return item.value;
      } else {
        return "未知";
      }
    },
    hCurrentChange(curPage) {
      // 更新页码
      this.page = curPage;
      // 重发请求
      this.loadEmployeeList();
    },
    hSizeChange(curSize) {
      // 更新每页几条
      this.size = curSize;
      // 重发请求
      this.loadEmployeeList();
    },
    dDel(id) {
      this.$confirm("你确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 调用api
          await delDemployees(id);
          if (this.list.length === 1) {
            this.page--;
            if (this.page === 0) {
              this.page = 1;
            }
          }
          // 刷新页面
          this.loadEmployeeList();
        })
        .catch(() => {
          // 用户取消退出
        });
    },
    // 新增
    hAdd() {
      this.showDialog = true;
    },
    // 取消按钮 隐藏
    hClose() {
      this.showDialog = false;
    },
    hUpdateEmpolyee() {
      this.showDialog = false;
      this.total++;
      // 最后一页
      this.page = Math.ceil(this.total / this.size);
      this.loadEmployeeList();
      // 添加成功，进入最后一页看数据
    },
    formatData(list) {
      const map = {
        id: "编号",
        password: "密码",
        mobile: "手机号",
        username: "姓名",
        timeOfEntry: "入职日期",
        formOfEmployment: "聘用形式",
        correctionTime: "转正日期",
        workNumber: "工号",
        departmentName: "部门",
        staffPhoto: "头像地址",
      };
      console.log(list);
      let header = [];
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = [];
      // 开始代码
      // 找到一个元素
      const one = list[0];
      if (!one) {
        return { header, data };
      }
      header = Object.keys(one).map((key) => {
        return map[key];
      });

      // data把list中每一个对象转成 对应的value数组
      data = list.map((obj) => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj["formOfEmployment"]; // 1, 2
        obj["formOfEmployment"] = EmployeENUM[key]; // hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj);
      });

      return { header, data };
    },
    // 导出Excel
    hExportExcel() {
      import("@/vendor/Export2Excel").then(async (excel) => {
        // excel表示导入的模块对象
        console.log(excel);
        // 1.发请求
        const res = await getEmployeeList({ page: this.page, size: this.size });
        // 2.格式转换 res.data.rows
        const { header, data } = this.formatData(res.data.rows);
        // 导出
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: "excel-list", // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: "xlsx", // 生成的文件类型
        });
      });
    },
  },
};
</script>